package com.example.warehouse.filter;


import com.alibaba.fastjson.JSON;
import com.example.warehouse.entity.Result;
import com.example.warehouse.utils.WarehouseConstants;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


public class LoginChechFilter implements Filter {
    private StringRedisTemplate redisTemplate;

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //过滤器拦截到请求的方法
    @Override
    public void doFilter(ServletRequest Request, ServletResponse Response, FilterChain chain) throws ServletException, IOException {


        HttpServletRequest request=(HttpServletRequest)Request;
        HttpServletResponse response=(HttpServletResponse)Response;
        //白名单请求直接放行
        List<String> pathlist=new ArrayList<>();//存放白名单
        pathlist.add("/captcha/captchaImage");
        pathlist.add("/login");
        pathlist.add("/product/img-upload");
        String path = request.getServletPath();
        if(pathlist.contains(path)||pathlist.contains("/img/upload")){
           chain.doFilter((ServletRequest) request, (ServletResponse) response);
           return;
        }

        //其他请求都校验是否携带token，以及判断redis中是否存在token的建
        String header = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //1>有，说明已登录，请求放行
        if(StringUtils.hasText(header)&&redisTemplate.hasKey(header)){
            chain.doFilter((ServletRequest) request, (ServletResponse) response);
            return;
        }
        //2>没有，说明未登录或token过期，请求补放行，并给前端做出响应

        Result result=Result.err(Result.CODE_ERR_UNLOGINED,"尚未登录");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        writer.flush();
        writer.close();
    }
}
